// 实验性函数，未经测试

import { Vector2 } from './_imports'
import type { Temp } from './_imports'

export { projectPointOnLine, projectPointOnRay }

// 根据公式 P = A + ((B - A) · (P - A)) / ||B - A||^2 * (B - A)
/** 计算点在线段上的投影点，不含线段的端点！ */
function projectPointOnLine(point: Vector2, line: Temp.Line): Vector2 | undefined {
  const { start, end } = line
  const PA = new Vector2().subVectors(point, start)
  const BA = new Vector2().subVectors(end, start)
  const t = PA.dot(BA) / BA.lengthSq()

  return t > 0 && t < 1 ? new Vector2(start.x + t * BA.x, start.y + t * BA.y) : undefined
}

/** 计算点在射线上的投影点 */
function projectPointOnRay(point: Vector2, ray: Temp.Ray): Vector2 {
  const { start, direction } = ray
  const PA = new Vector2().subVectors(point, start)
  const t = PA.dot(direction) / direction.lengthSq()
  return new Vector2(start.x + t * direction.x, start.y + t * direction.y)
}
